package com.yuyou.tas.lesson.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.tas.lesson.mapper.LessonClassMapper;
import com.yuyou.tas.lesson.mapper.LessonClassPlanChapterMapper;
import com.yuyou.tas.lesson.mapper.LessonClassPlanMapper;
import com.yuyou.tas.lesson.service.IBaseSchoolService;
import com.yuyou.tas.lesson.service.IBaseTermService;
import com.yuyou.tas.lesson.service.ILessonChapterService;
import com.yuyou.tas.lesson.service.ILessonClassAopService;
import com.yuyou.tas.lesson.service.ILessonClassChapterService;
import com.yuyou.tas.lesson.service.ILessonClassService;
import com.yuyou.tas.lesson.service.ILessonClassStudentService;
import com.yuyou.tas.lesson.service.ILessonClassUserRelService;
import com.yuyou.tas.lesson.service.ILessonService;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.service.AuthUserAPI;
import com.yuyou.tas.service.api.admin.service.CommJobAPI;
import com.yuyou.tas.service.api.lesson.dto.LessonClassSyncDTO;
import com.yuyou.tas.service.api.lesson.entity.BaseSchool;
import com.yuyou.tas.service.api.lesson.entity.BaseTrimester;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.service.api.lesson.entity.LessonChapter;
import com.yuyou.tas.service.api.lesson.entity.LessonClass;
import com.yuyou.tas.service.api.lesson.entity.LessonClassPlanChapter;
import com.yuyou.tas.service.api.lesson.entity.LessonClassUserRel;
import com.yuyou.tas.service.api.report.service.ExamModelAPI;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.bean.ResourceObj;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.enums.lesson.LessonClassEnums;
import com.yuyou.tas.util.exception.ResBoolSimpleInfoException;
import com.yuyou.tas.util.tool.DateUtil;
import com.yuyou.tas.util.tool.Sequence;

@Service
public class LessonClassServiceAopImpl implements ILessonClassAopService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());  
	
	@Autowired
	private LessonClassMapper lessonClassMapper;

	@Autowired
	private LessonClassPlanMapper lessonClassPlanMapper;

	@Autowired
	private LessonClassPlanChapterMapper  lessonClassPlanChapterMapper;

	@Autowired
	private ILessonClassUserRelService lessonClassUserRelService;

	@Autowired
	private ILessonService lessonService;

	@Autowired
	private ILessonChapterService lessonChapterService;

	@Autowired
	private IBaseSchoolService baseSchoolService;
	
	@Autowired
	private AuthUserAPI authUserAPI;
	
	@Autowired
	private IBaseTermService baseTermService;

	@Autowired
	private ILessonClassChapterService lessonClassChapterService;

	@Autowired
	private CommJobAPI commJobAPI;
	
	@Autowired
	private ILessonClassService lessonClassService;
	
	@Autowired
	private ILessonClassStudentService lessonClassStudentService;
	
	@Autowired
	private ExamModelAPI examModelAPI;
	
	@Override	
	@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
	public ResBoolSimpleInfo<String> sycnClassByOId(LessonClassSyncDTO dto) throws Exception {	
		Lesson lesson=lessonService.selectByOrgan7OId(dto.getLessonOId(), dto.getAuthOrganizationId());
		if(lesson==null){
			throw new ResBoolSimpleInfoException("班级("+dto.getoId()+")lessonOId("+dto.getLessonOId()+")的课程不存在");
		}
				
		LessonClass lessonClassSycn=lessonClassMapper.selectByOrgan7OId(dto.getoId(), dto.getAuthOrganizationId());			
		
		LessonClass lessonClass=new LessonClass();
		lessonClass.setoId(dto.getoId());
		lessonClass.setAuthOrganizationId(dto.getAuthOrganizationId());
		lessonClass.setLessonId(lesson.getId());
		lessonClass.setName(dto.getName());
		lessonClass.setNum(dto.getNum());
		lessonClass.setOpenTime(dto.getOpenTime());
		lessonClass.setCloseTime(dto.getCloseTime());
		lessonClass.setClassStatus(dto.getStatus());
		lessonClass.setStatus(dto.getProgressStatus());
		lessonClass.setClassStatus(dto.getStatus());
		
		if((dto.getUserOIds()==null || dto.getUserOIds().size()==0) && !lessonClass.getClassStatus().equals(LessonClassEnums.classStatus.cancel.getValue())){
			throw new ResBoolSimpleInfoException("班级("+dto.getoId()+"用户为空且状态不为作废");
		}
		
		BaseSchool baseSchool=baseSchoolService.selectByOrgan7OId(dto.getSchool(), dto.getAuthOrganizationId());
		if(baseSchool==null){
			throw new ResBoolSimpleInfoException("班级("+dto.getoId()+")school("+dto.getSchool()+")的班级不存在");
		}
		lessonClass.setBaseSchoolId(baseSchool.getId());

		//学期转换
		BaseTrimester baseTrimester=baseTermService.selectByOrgan7OId(dto.getTrimester(), dto.getAuthOrganizationId());
		if(baseTrimester ==null){
			throw new ResBoolSimpleInfoException("班级("+dto.getoId()+")trimester("+dto.getTrimester()+")的学期不存在");
		}
		lessonClass.setBaseTrimesterId(baseTrimester.getId());
					
		if(lessonClassSycn!=null){				

			if(!lessonClassSycn.getLessonId().equals(lesson.getId())){
				//换课程，重新生成班级讲次
				lessonClass.setLessonId(lesson.getId());
				lessonClass.setId(lessonClassSycn.getId());
				this.sycnClassCopyLesCha(lessonClass,dto.getAuthOrganizationId());
			}else{
				lessonClass.setLessonId(null);
			}		
//			if(lessonClassSycn.getIsSycn().equals(0)){
//				throw new ResBoolSimpleInfoException("班级("+lessonClassSycn.getoId()+")未同步，不更新");
//			}
			lessonClass.setId(lessonClassSycn.getId());
			lessonClass.setIsSycn(lesson.getStatus()==1?1:0);
			
			//已作废班级，删除模板范围
			if(lessonClass.getClassStatus().equals(LessonClassEnums.classStatus.cancel.getValue())){
				examModelAPI.deleteByClassId(lessonClass.getId(), lessonClass.getAuthOrganizationId());					
			}	
			lessonClassService.updateByPrimaryKeySelective(lessonClass);
		}else{
			//作废班级不插入
			if(!lessonClass.getClassStatus().equals(LessonClassEnums.classStatus.cancel.getValue())){
				lessonClass.setIsSycn(lesson.getStatus()==1?1:0);
				lessonClassService.insert(lessonClass);
				this.sycnClassCopyLesCha(lessonClass,dto.getAuthOrganizationId());
			}

		}
		
		//同步用户
		if(dto.getUserOIds()!=null && dto.getUserOIds().size()>0){
			syncClassUser(dto.getUserOIds(),lessonClass.getId(),dto.getAuthOrganizationId(),lesson);			
		}
		//查找班级学生，同步
		lessonClassStudentService.sycnClass(lessonClass.getId(),lessonClass.getoId(),lessonClass.getAuthOrganizationId());
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	/**
	 * 复制班级讲次和班级讲次课件
	 * @param lessonClass
	 * @param authOrganizationId
	 * @throws Exception
	 */
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void sycnClassCopyLesCha(LessonClass lessonClass,Long authOrganizationId) throws Exception{
		
		//先删除班级讲次
		lessonClassService.delLesCha(lessonClass.getId());
		
		// 引用课件信息
		lessonService.copyClassLesson(false,lessonClass.getId(),lessonClass.getLessonId(), null, new ResourceObj(null, lessonClass.getId(), authOrganizationId));
		// 复制讲次信息
		List<LessonChapter> lessonChapterList = lessonChapterService.findLessonChapterByLessId(lessonClass.getLessonId());
		for(LessonChapter lessonChapter : lessonChapterList){
			LessonClassPlanChapter lessonClassPlanChapter = new LessonClassPlanChapter();
			lessonClassPlanChapter.setId(Sequence.getSequence().nextId());
			lessonClassPlanChapter.setLessonClassId(lessonClass.getId());
			lessonClassPlanChapter.setLessonId(lessonChapter.getLessonId());
			lessonClassPlanChapter.setLessonChapterId(lessonChapter.getId());
			lessonClassPlanChapter.setSort(lessonChapter.getSort());
			lessonClassPlanChapter.setCreateTime(DateUtil.now());
			lessonClassPlanChapterMapper.insert(lessonClassPlanChapter);
		}
	}
	
	
	
	
	
	
	
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public void syncClassUser(List<Long> userOIds,Long classId,Long authOrganizationId,Lesson lesson) throws Exception{
		lessonClassUserRelService.delByLesClaId7Type(classId,AuthUserEnums.teacherType.lecturer.getValue());
		for(Long userOId:userOIds){
			AuthUser authUser=authUserAPI.selectByOrgan7OId(userOId, authOrganizationId);
			if(authUser==null){
				throw new ResBoolSimpleInfoException("班级("+classId+")userOId("+userOId+")的用户不存在");
			}
//			if(!authUser.getType().equals(AuthUserEnums.type.teacher.getValue())){
//				throw new ResBoolSimpleInfoException("班级("+classId+")userOId("+userOId+")的用户是非教师类型");
//			}			
			//用户科目与班级课程科目不一致
//			List<AuthUserSubjectDTO> subjectList=authUserAPI.findSubjectByAuthUserId(authUser.getId());
//			long dataSubjectC=subjectList.stream().filter(item ->item.getDataSubject().equals(lesson.getDataSubject())).count();
//			if(dataSubjectC==0){
//				throw new ResBoolSimpleInfoException("班级("+classId+")userOId("+userOId+")的用户的科目和班级课程科目不一致");
//			}
//			//用户年级与班级课程年级不一致
//	        Set<Long>sectionSet=authUserAPI.findUniSectionByUserId(authUser.getId());
//			long baseSectionC=sectionSet.stream().filter(item ->item.equals(lesson.getBaseSectionId())).count();
//			if(baseSectionC==0){
//				throw new ResBoolSimpleInfoException("班级("+classId+")userOId("+userOId+")的用户的年级和班级课程年级不一致");
//			}
			
			LessonClassUserRel lessonClassUserRel = new LessonClassUserRel();
			lessonClassUserRel.setAuthUserId(authUser.getId());
			lessonClassUserRel.setLessonClassId(classId);
			lessonClassUserRel.setType(AuthUserEnums.teacherType.lecturer.getValue());
			lessonClassUserRelService.insert(lessonClassUserRel);
		}
	}
	
	
}
